/**
 * Copyright 2021 Tianmian Tech. All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.welab.wefe.common.http;


import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;

import java.net.URI;

/**
 * A user-defined redirection policy is used to capture redirected addresses.
 *
 * @author Zane
 */
public class MyRedirectStrategy extends DefaultRedirectStrategy {

    private String currentLocation;

    @Override
    protected boolean isRedirectable(String method) {
        return super.isRedirectable(method);
    }

    @Override
    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        boolean result = super.isRedirected(request, response, context);
        // When no redirect is required, the URL is the request address.
        if (!result) {
            currentLocation = request.getRequestLine().getUri();
        }
        return result;
    }

    @Override
    public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
        URI uri = super.getLocationURI(request, response, context);
        currentLocation = uri.toString();
        return uri;
    }

    public String getCurrentLocation() {
        return currentLocation;
    }
}
